// Copyright 2022 a.o.smith ALL Rights Reserved
package com.liuxinlong.modules.assets.service.impl;

import com.liuxinlong.common.AosException;
import com.liuxinlong.common.SnowFlake;
import com.liuxinlong.constant.ThreadLocalConstants;
import com.liuxinlong.constant.TimeFormatConstants;
import com.liuxinlong.enums.InvestmentConfigTypeEnum;
import com.liuxinlong.enums.InvestmentLossRateEnum;
import com.liuxinlong.enums.InvestmentTurnoverEnum;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.modules.assets.service.InvestmentConfigService;
import com.liuxinlong.modules.common.entity.CommonSelectDto;
import com.liuxinlong.modules.dao.InvestmentCommonConfigDao;
import com.liuxinlong.modules.dao.InvestmentConfigDao;
import com.liuxinlong.modules.entity.AssetsInvestmentCommonConfig;
import com.liuxinlong.modules.entity.AssetsInvestmentConfig;
import com.liuxinlong.modules.entity.User;
import com.liuxinlong.utils.ObjectUtils;
import com.liuxinlong.utils.ThreadlocalUtils;
import com.liuxinlong.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 固资项目配置管理业务接口层实现
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2024-09-06
 */
@Service
@Slf4j
public class InvestmentConfigServiceImpl implements InvestmentConfigService {

    @Autowired
    private InvestmentConfigDao investmentConfigDao;

    @Autowired
    private InvestmentCommonConfigDao investmentCommonConfigDao;

    @Override
    public List<Map<String, Object>> pageInvestmentConfigInfo(Map<String, Object> queryParam) {
        List<AssetsInvestmentConfig> configList = investmentConfigDao.pageInvestmentConfigInfo(queryParam);
        int startNum = (int) queryParam.get("startNum");
        return completeResult(configList, startNum);
    }

    @Override
    public int getInvestmentConfigInfoCount(Map<String, Object> queryParam) {
        return investmentConfigDao.getInvestmentConfigInfoCount(queryParam);
    }

    @Override
    public void addInvestmentConfigInfo(AssetsInvestmentConfig investmentConfig) {
//        Map<String,Object> queryParam = new HashMap<>();
//        if (investmentConfig.getConfigType() + 4 == InvestmentConfigTypeEnum.TYPE_MARGIN.getValue()) {
//            queryParam.put("")
//        }
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        investmentConfig.setId(SnowFlake.nextIdStr());
        investmentConfig.setCreateUser(currentUser.getId());
        investmentConfig.setCreateTime(currentTime);
        investmentConfig.setStatus(2);
        investmentConfigDao.insert(investmentConfig);
    }

    @Override
    public void updateInvestmentConfigInfo(AssetsInvestmentConfig investmentConfig) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        AssetsInvestmentConfig config = investmentConfigDao.selectById(investmentConfig.getId());
        if (config.getStatus() == 1) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "启用状态配置信息不可修改！");
        }
        investmentConfig.setCreateUser(config.getCreateUser());
        investmentConfig.setCreateTime(config.getCreateTime());
        investmentConfig.setUpdateUser(currentUser.getId());
        investmentConfig.setUpdateTime(currentTime);
        investmentConfig.setStatus(config.getStatus());
        investmentConfigDao.updateById(investmentConfig);
    }

    @Override
    public void deleteInvestmentConfigInfo(String id) {
        AssetsInvestmentConfig config = investmentConfigDao.selectById(id);
        if (config.getStatus() == 1) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "启用状态配置信息不可删除！");
        }
        investmentConfigDao.deleteById(id);
    }

    @Override
    public void updateInvestmentConfigStatus(String id, int targetStatus) {
        AssetsInvestmentConfig config = investmentConfigDao.selectById(id);
        if (ObjectUtils.isEmpty(config)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改失败，配置不存在！");
        }
        config.setStatus(targetStatus);
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        config.setUpdateUser(currentUser.getId());
        config.setUpdateTime(currentTime);
        investmentConfigDao.updateById(config);
    }

    @Override
    public List<Map<String, Object>> pageInvestmentCommonConfigInfo(Map<String, Object> queryParam) {
        List<AssetsInvestmentCommonConfig> configList = investmentCommonConfigDao.pageInvestmentCommonConfigInfo(queryParam);
        int startNum = (int) queryParam.get("startNum");
        return completeCommonResult(configList, startNum);
    }

    @Override
    public int getInvestmentCommonConfigInfoCount(Map<String, Object> queryParam) {
        return investmentCommonConfigDao.getInvestmentCommonConfigInfoCount(queryParam);
    }

    @Override
    public void addInvestmentCommonConfigInfo(AssetsInvestmentCommonConfig investmentConfig) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        investmentConfig.setId(SnowFlake.nextIdStr());
        investmentConfig.setCreateUser(currentUser.getId());
        investmentConfig.setCreateTime(currentTime);
        investmentConfig.setStatus(2);
        investmentCommonConfigDao.insert(investmentConfig);
    }

    @Override
    public void updateInvestmentCommonConfigInfo(AssetsInvestmentCommonConfig investmentConfig) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        AssetsInvestmentCommonConfig config = investmentCommonConfigDao.selectById(investmentConfig.getId());
        if (config.getStatus() == 1) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "启用状态配置信息不可修改！");
        }
        investmentConfig.setCreateUser(config.getCreateUser());
        investmentConfig.setCreateTime(config.getCreateTime());
        investmentConfig.setUpdateUser(currentUser.getId());
        investmentConfig.setUpdateTime(currentTime);
        investmentConfig.setStatus(config.getStatus());
        investmentCommonConfigDao.updateById(investmentConfig);
    }

    @Override
    public void deleteInvestmentCommonConfigInfo(String id) {
        AssetsInvestmentCommonConfig config = investmentCommonConfigDao.selectById(id);
        if (config.getStatus() == 1) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "启用状态配置信息不可删除！");
        }
        investmentCommonConfigDao.deleteById(id);
    }

    @Override
    public List<CommonSelectDto> getCommonConfig(int configType) {
        Map<String, Object> query = new HashMap<>();
        query.put("configType", configType);
        query.put("status", 1);
        query.put("startNum", 0);
        query.put("pageSize", 10000);
        List<AssetsInvestmentCommonConfig> originList = investmentCommonConfigDao.pageInvestmentCommonConfigInfo(query);
        List<CommonSelectDto> resultList = new ArrayList<>(originList.size());
        for (AssetsInvestmentCommonConfig config : originList) {
            CommonSelectDto dto = new CommonSelectDto();
            dto.setId(config.getId());
            dto.setLabel(config.getConfigName());
            dto.setValue(config.getId());
            dto.setName(config.getConfigName());
            resultList.add(dto);
        }
        return resultList;
    }

    @Override
    public Map<String, Object> getConfigInfo(Map<String, Object> queryParam) {
        int configType = (int) queryParam.get("configType") - 4;
        queryParam.put("configType", configType);
        queryParam.put("status", 1);
        queryParam.put("startNum", 0);
        queryParam.put("pageSize", 10000);
        List<AssetsInvestmentConfig> configList = investmentConfigDao.pageInvestmentConfigInfo(queryParam);
        if (ObjectUtils.isEmpty(configList)) {
//            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR,"配置不存在");
            return new HashMap<>();
        }
        return ObjectUtils.object2Map(configList.get(0));
    }

    @Override
    @Transactional
    public void updateInvestmentCommonConfigStatus(String id, int targetStatus) {
        AssetsInvestmentCommonConfig config = investmentCommonConfigDao.selectById(id);
        if (ObjectUtils.isEmpty(config)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改失败，配置不存在！");
        }
        config.setStatus(targetStatus);
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        config.setUpdateUser(currentUser.getId());
        config.setUpdateTime(currentTime);
        investmentCommonConfigDao.updateById(config);
    }

    @Override
    public Map<String, Map<String, String>> getCommonConfigMap() {
        return investmentCommonConfigDao.getCommonConfigMap();
    }

    @Override
    public List<Map<String, Object>> getLossConfigInfo(Map<String, Object> queryParam) {
        queryParam.put("configType", 2);
        queryParam.put("status", 1);
        queryParam.put("startNum", 0);
        queryParam.put("pageSize", 10000);
        List<AssetsInvestmentConfig> configList = investmentConfigDao.pageInvestmentConfigInfo(queryParam);
        if (configList.isEmpty()) {
            return new ArrayList<>();
        }
        if (configList.size() > 2) {
            return new ArrayList<>();
        }
        Map<String,Object> queryBrand = new HashMap<>();
        queryBrand.put("configType", InvestmentConfigTypeEnum.TYPE_BRAND.getValue());
        queryBrand.put("status", 1);
        queryBrand.put("startNum", 0);
        queryBrand.put("pageSize", 100);
        List<AssetsInvestmentCommonConfig> brandList = investmentCommonConfigDao.pageInvestmentCommonConfigInfo(queryBrand);
        Map<String,String> brandMap = new HashMap<>();
        for (AssetsInvestmentCommonConfig brandConfig: brandList) {
            brandMap.put(brandConfig.getId(),brandConfig.getConfigName());
        }
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (InvestmentLossRateEnum item : InvestmentLossRateEnum.values()) {
            Map<String,Object> dto = new HashMap<>();
            dto.put("rateType",item.getValue());
            dto.put("rateName",item.getName());
            for (AssetsInvestmentConfig config: configList){
                String value = item.getValue() == InvestmentLossRateEnum.SALES.getValue() ? config.getParamOne()
                        : item.getValue() == InvestmentLossRateEnum.SERVICE.getValue() ? config.getParamTwo()
                        : item.getValue() == InvestmentLossRateEnum.DIRECT.getValue() ? config.getParamThree()
                        : item.getValue() == InvestmentLossRateEnum.INDIRECT.getValue() ? config.getParamFour()
                        : item.getValue() == InvestmentLossRateEnum.ADVERTISING.getValue() ? config.getParamFive()
                        : item.getValue() == InvestmentLossRateEnum.ENGINEERING.getValue() ? config.getParamSix()
                        : item.getValue() == InvestmentLossRateEnum.PRODUCT.getValue() ? config.getParamSeven() : "0";
                if (StringUtils.equals(brandMap.get(config.getConfigBrand()),"史密斯")) {
                    dto.put("rateAmountSms",value);
                } else  if (StringUtils.equals(brandMap.get(config.getConfigBrand()),"佳尼特")) {
                    dto.put("rateAmountJnt",value);
                }
            }
            dataList.add(dto);
        }
        return dataList;
    }

    @Override
    public List<Map<String, Object>> getTurnoverConfigInfo(Map<String, Object> queryParam) {
        queryParam.put("configType", 3);
        queryParam.put("status", 1);
        queryParam.put("startNum", 0);
        queryParam.put("pageSize", 10000);
        List<AssetsInvestmentConfig> configList = investmentConfigDao.pageInvestmentConfigInfo(queryParam);
        if (configList.isEmpty()) {
            return new ArrayList<>();
        }
        AssetsInvestmentConfig configInfo = configList.get(0);
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (InvestmentTurnoverEnum item : InvestmentTurnoverEnum.values()) {
            Map<String, Object> dto = ObjectUtils.object2Map(item);
            dto.put("turnoverType",item.getValue());
            dto.put("typeName", item.getName());
            dto.put("days", item.getValue() == InvestmentTurnoverEnum.AR.getValue() ? configInfo.getParamOne() :
                    item.getValue() == InvestmentTurnoverEnum.INVENTORY.getValue() ? configInfo.getParamTwo() :
                            item.getValue() == InvestmentTurnoverEnum.AP.getValue() ? configInfo.getParamThree() : null);
            dataList.add(dto);
        }
        return dataList;
    }

    /**
     * 补全数据
     *
     * @param originalList 原始数据
     * @param startNum     数据起始值
     * @return 补全数据列表
     */
    private List<Map<String, Object>> completeResult(List<AssetsInvestmentConfig> originalList, int startNum) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        int sort = startNum + 1;
        for (AssetsInvestmentConfig config : originalList) {
            Map<String, Object> item = ObjectUtils.object2Map(config);
            item.put("sort", sort);
            item.put("configTypeName", InvestmentConfigTypeEnum.getNameByValue(config.getConfigType() + 4));
            item.put("statusName", config.getStatus() == 1 ? "可用" : "不可用");
            resultList.add(item);
            sort++;
        }
        return resultList;
    }

    /**
     * 补全数据
     *
     * @param originalList 原始数据
     * @param startNum     数据起始值
     * @return 补全数据列表
     */
    private List<Map<String, Object>> completeCommonResult(List<AssetsInvestmentCommonConfig> originalList, int startNum) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        int sort = startNum + 1;
        for (AssetsInvestmentCommonConfig config : originalList) {
            Map<String, Object> item = ObjectUtils.object2Map(config);
            item.put("sort", sort);
            item.put("configTypeName", InvestmentConfigTypeEnum.getNameByValue(config.getConfigType()));
            item.put("statusName", config.getStatus() == 1 ? "可用" : "不可用");
            resultList.add(item);
            sort++;
        }
        return resultList;
    }


}
